package dshop.action.admin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import appbase.exception.BizzException;
import appbase.jfinal.ext.ApiBaseController;
import appbase.jfinal.ext.RecordKit;
import dshop.AppConst;
import dshop.interceptor.ApiAuthInterceptor;
import dshop.interceptor.ApiReadBodyParamInterceptor;
import dshop.model.draw.DrawDetail;
import dshop.service.CommissionService;
import dshop.service.RedisService;

@Before({ ApiReadBodyParamInterceptor.class, ApiAuthInterceptor.class })
public class DrawCashAction extends ApiBaseController {

	public void list() {
		int status = getParaToInt("status", 0);
		String keyWord = getPara("keyWord", "").trim();
		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];

		String select = " select d.id, d.user_id, d.money, d.status,d.draw_type, d.bank, d.account_no, d.account_name, d.create_time, d.draw_time, d.remark, d.operator, d.operator_time,d.sign, concat(m.last_name, m.first_name) as full_name, m.phone ";
		String where = " from draw_detail d  " + " inner join member_general_info m on d.user_id = m.account_id "
				+ " where 1 = 1 ";

		String orderBy = " order by d.create_time desc, d.id desc ";

		List<Object> params = new ArrayList<Object>();

		if (!keyWord.isEmpty()) {
			where += " and m.phone = ? ";
			params.add(keyWord);
		}
		if (status > 0) {
			where += " and d.status = ? ";
			params.add(status);
		}
		if (!columnOrder.isEmpty()) {
			orderBy = "order by " + columnProp + " " + columnOrder;
		}
		Page<Record> page = page(select, where + orderBy, params.toArray());
		List<Record> list = page.getList();

		RecordKit.setAttrStrVal(list, DrawDetail.STATUS_STR_MAP, "status", "status_str");
//		RecordKit.putDateStr(list, "create_time", "create_time_str", "yyyy-MM-dd HH:mm");
//		RecordKit.putDateStr(list, "draw_time", "draw_time_str", "yyyy-MM-dd HH:mm");

		for (Record r : list) {
			if (DrawDetail.checkSign(r.getInt("id"), r.getInt("user_id"), r.getBigDecimal("money"),
					r.getStr("account_no"), r.getStr("account_name"), r.getInt("status"), r.getDate("create_time"),
					r.getStr("sign"))) {
				r.set("is_valid", AppConst.STATUS_VAL_YES);
			} else {
				r.set("is_valid", AppConst.STATUS_VAL_NO);
			}
		}

		renderSuccess();
	}

	/**
	 * 确认提现申请
	 */
	@Before(Tx.class)
	public void confirm() {
		int drawId = getParaToInt("id");

		try {
			DrawDetail.confirm(drawId);
		} catch (BizzException e) {
			e.printStackTrace();
			renderFail(e.getMessage());
			return;
		}

		String userPhone = RedisService.getApiUserPhone(getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID));
		DrawDetail.updateOperator(userPhone, drawId);
		renderSuccess("操作成功，标记为已确认");
	}

	/**
	 * 提现成功
	 */
	@Before(Tx.class)
	public void setSuccess() {
		int drawId = getParaToInt("id");

		DrawDetail draw = DrawDetail.dao.findById(drawId);
		if (draw == null || !draw.canDraw()) {
			renderFail("同一个提现申请不能处理两次");
			return;
		}

		// int userId = draw.getInt("userId");
		BigDecimal money = draw.getBigDecimal("money");
		String remark = "";

		try {
			DrawDetail.update(drawId, DrawDetail.STATUS_DRAW_SUCCESS, remark);
		} catch (BizzException e) {
			e.printStackTrace();
			renderFail(e.getMessage());
			return;
		}
		CommissionService.onDrawSuccess(drawId, money);

		// MsgService.onDrawCashSuccess(userId, drawId);

		String userPhone = RedisService.getApiUserPhone(getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID));
		DrawDetail.updateOperator(userPhone, drawId);
		renderSuccess("操作成功，已标记为提现成功");
	}

	/**
	 * 提现失败
	 */
	@Before(Tx.class)
	public void setFail() {
		int id = getParaToInt("id");
		String remark = getPara("remark", "").trim();

		if (remark.isEmpty()) {
			renderFail("请填写提现失败原因");
			return;
		}

		DrawDetail draw = DrawDetail.dao.findById(id);
		if (draw == null) {
			renderFail("同一个提现申请不能处理两次");
			return;
		}
		int statuz = draw.getInt("status");
		if (statuz != DrawDetail.STATUS_APPLY && statuz != DrawDetail.STATUS_CONFIRM) {
			renderFail("状态不对");
			return;
		}

		int drawId = draw.getInt("id");
		int userId = draw.getInt("user_id");
		BigDecimal money = draw.getBigDecimal("money");

		try {
			DrawDetail.update(id, DrawDetail.STATUS_FAIL, remark);
		} catch (BizzException e) {
			e.printStackTrace();
			renderFail(e.getMessage());
			return;
		}
		CommissionService.onDrawFail(userId, drawId, money);

		// MsgService.onDrawCashFail(userId, drawId, remark);

		renderSuccess("操作成功，已标记为提现失败");
	}

}
